package com.yonyou.pmclouds.projecttype.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.projecttype.entity.ProjectTypeVO;
import com.yonyou.pmclouds.projecttype.rmiitf.ProjectTypeMaintain;
import com.yonyou.pmclouds.projecttype.rmiitf.ProjectTypeQuery;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/projectType")
public class ProjectTypeExtendController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectTypeMaintain maintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectTypeQuery query;

    //添加项目类别
    @RequestMapping("/addProjectType")
    public ProjectTypeVO addProjectType(@RequestBody @Validated(ProjectTypeVO.OutterValid.class) ProjectTypeVO projectTypeVO,
                                    HttpServletRequest request) throws BusinessException {
        if (projectTypeVO.getPkTenant()==null){
            //添加租户
            setTenantInfo(projectTypeVO,request);
        }

        return maintain.insert(projectTypeVO);

    }
    //补充租户ID
    private void setTenantInfo(ProjectTypeVO projectTypeVO,HttpServletRequest request) throws BusinessException{
        String tenantId = RuntimeEnvironment.getTenantId();
        if(StringUtils.isEmpty(tenantId)){
            throw new BusinessException("未找到对应租户信息");
        }
        projectTypeVO.setPkTenant(tenantId);
    }
    //修改项目类别
    @RequestMapping("/updateProjectType")
    public ProjectTypeVO updateProjectType(@RequestBody @Validated(ProjectTypeVO.OutterValid.class) ProjectTypeVO projectTypeVO,
                                          HttpServletRequest request) throws BusinessException {

        if (projectTypeVO.getPkTenant()==null){
            //添加租户
            setTenantInfo(projectTypeVO,request);
        }


        return maintain.update(projectTypeVO);
    }
    //删除项目类别
    @RequestMapping("/removeProjectType")
    public String removeProjectType(@RequestBody @Validated(ProjectTypeVO.OutterValid.class) ProjectTypeVO projectTypeVO,
                                  HttpServletRequest request) throws BusinessException {

        if (projectTypeVO.getPkTenant()==null){
            //添加租户
            setTenantInfo(projectTypeVO,request);
        }else {
            RuntimeEnvironment.setTenantId(projectTypeVO.getPkTenant());
        }

        return maintain.delete(projectTypeVO.getPkProjectType(), projectTypeVO.getChangeFlag());
    }
    //启动
    @RequestMapping("/enable")
    public Object enable(@RequestBody ProjectTypeVO projectTypeVO) throws BusinessException {
        if (projectTypeVO==null){
            throw new BusinessException("传参错误");
        }
        if (projectTypeVO.getPkTenant()!=null){
            RuntimeEnvironment.setTenantId(projectTypeVO.getPkTenant());
        }
        ProjectTypeVO enable = maintain.enable(projectTypeVO);
        return enable;
    }
    //停止
    @RequestMapping("/disEnable")
    public Object disEnable(@RequestBody ProjectTypeVO projectTypeVO) throws BusinessException {
        if (projectTypeVO==null){
            throw new BusinessException("传参错误");
        }
        if (projectTypeVO.getPkTenant()!=null){
            RuntimeEnvironment.setTenantId(projectTypeVO.getPkTenant());
        }
        ProjectTypeVO[] disEnable = maintain.disEnable(projectTypeVO);
        return tree(disEnable,projectTypeVO.getPkParent());
    }




    //根据项目类型ID查询项目类型数据
    @RequestMapping("/getByPkProjectType")
    public ProjectTypeVO getByPkProjectType(String pkProjectType) throws BusinessException {
        ProjectTypeVO projectTypeVO = query.queryById(pkProjectType);
        return projectTypeVO;
    }
    //根据项目来源ID查询项目类型数据
    @RequestMapping("/getByPkSrc")
    public ProjectTypeVO getByPkSrc(String pkSrc) throws BusinessException {
        ProjectTypeVO projectTypeVO = query.queryByPkSrc(pkSrc);
        return projectTypeVO;
    }
    //根据项目类型ID数组查询项目类型名称
    @RequestMapping("/getByIds")
    public Object getByIds(String[] ids) throws BusinessException {
        Map<String, String> stringStringMap = query.queryNamesByIds(ids);
        return stringStringMap;
    }
    //根据项目类型ID查询项目类型名称
    public Object getById(String id) throws BusinessException {
        String sname = query.queryNameById(id);
        return sname;
    }


    //查询所有项目类型档案
    @RequestMapping("/list")
    public ProjectTypeVO[] getList(@RequestParam(value = "status", required = false) Integer status) throws BusinessException {
        ProjectTypeVO[] projectTypeVOS = query.queryList(RuntimeEnvironment.getTenantId(), (byte) 2);
        return tree(projectTypeVOS,StringUtils.EMPTY);
    }

    //建立树形
    public ProjectTypeVO[] tree(ProjectTypeVO[] projectTypeVOS,String pkParent){
        //判断是否为空
        if (ArrayUtils.isEmpty(projectTypeVOS)){
            return projectTypeVOS;
        }else {
        //创建一个key为pkParent，value为List<ProjectTypeVO>的map集合
            Map<String, List<ProjectTypeVO>> chirdrenMap=new HashMap<String, List<ProjectTypeVO>>();
            //创建一个key为pkProjectType,value为scode的Map集合
            Map<String,String> scodeMap=new HashMap<>();
            for (ProjectTypeVO projectTypeVO:projectTypeVOS){
                scodeMap.put(projectTypeVO.getPkProjectType(),projectTypeVO.getScode());
            }
            for (ProjectTypeVO projectTypeVO:projectTypeVOS){
                String parent=projectTypeVO.getPkParent();
                if (parent!=null){
                    //前端需要子节点中存放父节点的编码
                    projectTypeVO.setPcode(scodeMap.get(parent));
                }else {
                    parent=StringUtils.EMPTY;
                }
                List<ProjectTypeVO> list = chirdrenMap.get(parent);
                if (list==null){
                    list=new ArrayList<ProjectTypeVO>();
                    chirdrenMap.put(parent,list);
                }
                    list.add(projectTypeVO);

            }
            for (ProjectTypeVO projectTypeVO:projectTypeVOS){
                List<ProjectTypeVO> list = chirdrenMap.get(projectTypeVO.getPkProjectType());
                if (list!=null){
                    projectTypeVO.setProjectTypeVOS(list.toArray(new ProjectTypeVO[list.size()]));
                }
            }
            //获得根节点
            List<ProjectTypeVO> list = chirdrenMap.get(StringUtils.EMPTY);
            if (list==null){
               list=chirdrenMap.get(pkParent);
            }
            if (list==null){
                return new ProjectTypeVO[0];
            }else {
                return list.toArray(new ProjectTypeVO[list.size()]);
            }
        }
    }

    /**
     * 组织下的项目类型
     */
    @RequestMapping("/queryByOrg")
    public ProjectTypeVO[] queryByOrg(String pkOrg) throws BusinessException {
        return query.queryByOrg(pkOrg);
    }




}
